<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="12">
            <h3>{{ bookName }} - 错题列表</h3>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-refresh"
                @click="syncWrongQuestions"
              >同步错题</el-button>
              <el-button
                type="success"
                icon="el-icon-edit"
                @click="handlePractice"
              >开始练习</el-button>
              <el-button
                type="info"
                icon="el-icon-data-line"
                @click="showStats"
              >查看统计</el-button>
            </el-button-group>
          </el-col>
        </el-row>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部错题" name="all"></el-tab-pane>
        <el-tab-pane label="未掌握" name="unmastered"></el-tab-pane>
        <el-tab-pane label="已掌握" name="mastered"></el-tab-pane>
      </el-tabs>

      <el-row :gutter="20" class="mb-20">
        <el-col :span="8">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索题目"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleQuery"
            />
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-select
            v-model="queryParams.typeId"
            placeholder="选择题型"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-select
            v-model="queryParams.difficult"
            placeholder="选择难度"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in difficultyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
      </el-row>

      <!-- 错题卡片列表 -->
      <div v-loading="loading">
        <el-row :gutter="20">
          <el-col
            v-for="record in recordList"
            :key="record.id"
            :span="24"
            class="mb-20"
          >
            <el-card class="record-card" shadow="hover">
              <div slot="header" class="clearfix">
                <el-checkbox
                  v-model="selectedRecordIds"
                  :label="record.id"
                  @change="handleSelectChange(record)"
                  class="record-checkbox"
                ></el-checkbox>
                <span class="record-title">{{ record.question.title }}</span>
                <div style="float: right;">
                  <el-tag size="small" style="margin-right: 5px;">{{ record.question.typeName }}</el-tag>
                  <el-tag size="small" :type="record.isMastered ? 'success' : 'danger'">
                    {{ record.isMastered ? '已掌握' : '未掌握' }}
                  </el-tag>
                </div>
              </div>

              <div class="record-content">
                <formula-renderer :html="record.question.content" />
              </div>

              <div class="record-meta">
                <div class="meta-item">
                  <span class="meta-label">来源考试:</span>
                  <span class="meta-value">{{ record.examName }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">错误次数:</span>
                  <span class="meta-value">{{ record.wrongCount }}次</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">上次错误:</span>
                  <span class="meta-value">{{ record.lastWrongTime }}</span>
                </div>
              </div>

              <div class="record-actions">
                <el-button-group>
                  <el-button
                    size="mini"
                    @click="handleDetail(record)"
                  >查看详情</el-button>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handlePracticeOne(record)"
                  >练习本题</el-button>
                  <el-button
                    size="mini"
                    :type="record.isMastered ? 'danger' : 'success'"
                    @click="toggleMastered(record)"
                  >{{ record.isMastered ? '标记未掌握' : '标记已掌握' }}</el-button>
                  <el-dropdown @command="handleRecommend(record, $event)">
                    <el-button size="mini" type="info">
                      智能推荐<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="similar">相似题目</el-dropdown-item>
                      <el-dropdown-item command="knowledge">同知识点不同难度</el-dropdown-item>
                      <el-dropdown-item command="difficulty">同难度不同知识点</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-button-group>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>

      <!-- 同步错题对话框 -->
      <el-dialog
        title="同步错题"
        :visible.sync="syncDialogVisible"
        width="80%"
      >
        <el-table
          :data="wrongAnswers"
          @selection-change="handleSelectionChange"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="question.title" label="题目" min-width="200">
            <template slot-scope="scope">
              <div v-html="scope.row.question.title"></div>
            </template>
          </el-table-column>
          <el-table-column prop="exam.title" label="来源考试" width="150"></el-table-column>
          <el-table-column label="错误次数" width="100">
            <template slot-scope="scope">
              {{ scope.row.wrongCount || 1 }}次
            </template>
          </el-table-column>
          <el-table-column prop="submitTime" label="考试时间" width="150">
            <template slot-scope="scope">
              {{ formatTime(scope.row.exam.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handlePreview(scope.row)"
              >预览</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSync" :loading="loading">同步选中错题</el-button>
        </div>
      </el-dialog>

      <!-- 题目详情对话框 -->
      <el-dialog
        :title="detailTitle"
        :visible.sync="detailVisible"
        width="80%"
        top="5vh"
      >
        <question-detail :question="currentQuestion"/>
        <div slot="footer" class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </el-dialog>

      <!-- 推荐题目对话框 -->
      <el-dialog
        :title="recommendTitle"
        :visible.sync="recommendVisible"
        width="80%"
        top="5vh"
      >
        <el-table
          :data="recommendedQuestions"
          @selection-change="handleRecommendSelectionChange"
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="title" label="题目" min-width="200">
            <template slot-scope="scope">
              <div class="question-title">{{ scope.row.title }}</div>
              <formula-renderer :html="scope.row.content" class="question-content" />
            </template>
          </el-table-column>
          <el-table-column prop="typeName" label="题型" width="120"></el-table-column>
          <el-table-column label="难度" width="100">
            <template slot-scope="scope">
              <el-tag :type="getDifficultyTagType(scope.row.difficult)" size="small">
                {{ getDifficultyText(scope.row.difficult) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="知识点" min-width="150">
            <template slot-scope="scope">
              {{ scope.row.categories || '无' }}
            </template>
          </el-table-column>
          <el-table-column label="相似度" width="100" v-if="recommendTitle.includes('相似')">
            <template slot-scope="scope">
              <el-progress
                :percentage="Math.round((scope.row.similarity || 0) * 100)"
                :format="formatSimilarity"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handlePreviewRecommend(scope.row)"
              >预览</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="recommendVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handlePracticeRecommended"
            :disabled="selectedRecommendedQuestions.length === 0"
          >
            练习选中题目({{ selectedRecommendedQuestions.length }})
          </el-button>
        </div>
      </el-dialog>

      <!-- 统计面板 -->
      <el-drawer
        title="错题统计"
        :visible.sync="statsVisible"
        direction="rtl"
        size="50%"
      >
        <wrong-question-stats :book-id="bookId" :user-id="$store.state.user.id"/>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import { pageRecords, markMastered, recommendQuestions, getWrongAnswers, syncWrongAnswers } from '@/api/wrongQuestion'
import { listQuestionTypes } from '@/api/question2/question'
import QuestionDetail from '@/views/question2/list/QuestionDetail'
import QuestionList from '@/views/question2/list'
import WrongQuestionStats from './StatsPanel'
import { formatTime } from '@/utils'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue"

export default {
  name: 'RecordList',
  components: { FormulaRenderer, QuestionDetail, QuestionList, WrongQuestionStats },
  data() {
    return {
      // 路由参数
      bookId: null,
      bookName: '',
      // 活动标签页
      activeTab: 'all',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        typeId: undefined,
        difficult: undefined,
        isMastered: undefined
      },
      // 错题记录列表
      recordList: [],
      total: 0,
      loading: true,
      // 选中记录
      selectedRecordIds: [],
      // 题型选项
      typeOptions: [],
      // 难度选项
      difficultyOptions: [
        {value: 1, label: '简单'},
        {value: 2, label: '偏易'},
        {value: 3, label: '中等'},
        {value: 4, label: '偏难'},
        {value: 5, label: '困难'}
      ],
      // 同步错题对话框
      syncDialogVisible: false,
      wrongAnswers: [],
      selectedAnswers: [],
      // 详情对话框
      detailVisible: false,
      currentQuestion: null,
      detailTitle: '',
      // 推荐题目对话框
      recommendVisible: false,
      recommendedQuestions: [],
      selectedRecommendedQuestions: [],
      recommendTitle: '',
      // 统计面板
      statsVisible: false
    }
  },
  created() {
    this.bookId = this.$route.query.bookId
    this.getBookInfo()
    this.getList()
    this.getTypeOptions()
  },
  methods: {
    // 预览题目
    handlePreview(answer) {
      this.currentQuestion = answer.question
      this.detailTitle = `题目预览 - ${answer.question.id}`
      this.detailVisible = true
    },

    // 预览推荐题目
    handlePreviewRecommend(question) {
      this.currentQuestion = question
      this.detailTitle = `题目预览 - ${question.id}`
      this.detailVisible = true
    },

    formatTime,

    // 格式化相似度显示
    formatSimilarity(percentage) {
      return `${percentage}%`
    },

    // 获取难度文本
    getDifficultyText(difficult) {
      const map = {
        1: '简单',
        2: '偏易',
        3: '中等',
        4: '偏难',
        5: '困难'
      }
      return map[difficult] || '未知'
    },

    // 获取难度标签类型
    getDifficultyTagType(difficult) {
      const map = {
        1: 'success',
        2: '',
        3: 'primary',
        4: 'warning',
        5: 'danger'
      }
      return map[difficult] || ''
    },

    // 获取错题本信息
    getBookInfo() {
      this.bookName = this.$route.query.bookName || '我的错题本'
    },

    // 获取错题记录列表
    getList() {
      this.loading = true
      const params = {...this.queryParams, bookId: this.bookId}
      pageRecords(params)
        .then(response => {
          this.recordList = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 获取题型选项
    getTypeOptions() {
      listQuestionTypes().then(response => {
        this.typeOptions = response.data
      })
    },

    // 标签切换
    handleTabClick(tab) {
      switch (tab.name) {
        case 'unmastered':
          this.queryParams.isMastered = 0
          break
        case 'mastered':
          this.queryParams.isMastered = 1
          break
        default:
          this.queryParams.isMastered = undefined
          break
      }
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 选中变化
    handleSelectChange(record) {
      // 可以在这里处理选中逻辑
    },

    // 同步错题
    syncWrongQuestions() {
      this.loading = true
      getWrongAnswers(this.$store.state.user.id)
        .then(response => {
          this.wrongAnswers = response.data
          this.syncDialogVisible = true
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 表格选中变化
    handleSelectionChange(selection) {
      this.selectedAnswers = selection.map(item => item.id)
    },

    // 推荐题目选中变化
    handleRecommendSelectionChange(selection) {
      this.selectedRecommendedQuestions = selection.map(item => item.id)
    },

    // 提交同步
    submitSync() {
      if (this.selectedAnswers.length === 0) {
        this.$message.warning('请选择要同步的错题')
        return
      }

      this.loading = true
      syncWrongAnswers(this.bookId, this.selectedAnswers)
        .then(response => {
          this.$message.success(response.msg || '同步成功')
          this.syncDialogVisible = false
          this.getList()
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 查看详情
    handleDetail(record) {
      this.currentQuestion = record.question
      this.detailTitle = '题目详情 - ' + record.question.id
      this.detailVisible = true
    },

    // 标记掌握状态
    toggleMastered(record) {
      const newStatus = record.isMastered ? 0 : 1
      markMastered(record.id, newStatus).then(() => {
        this.$message.success('操作成功')
        record.isMastered = newStatus
      })
    },

    // 智能推荐
    handleRecommend(record, command) {
      let strategy, title
      switch (command) {
        case 'similar':
          strategy = 1
          title = `与"${record.question.title}"相似的题目`
          break
        case 'knowledge':
          strategy = 2
          title = `与"${record.question.title}"同知识点的题目`
          break
        case 'difficulty':
          strategy = 3
          title = `与"${record.question.title}"同难度的题目`
          break
        default:
          strategy = 1
          title = '推荐题目'
      }

      this.loading = true
      recommendQuestions(record.id, 5, strategy).then(response => {
        this.recommendedQuestions = response.data
        this.recommendTitle = title
        this.recommendVisible = true
        this.selectedRecommendedQuestions = [] // 清空之前的选择
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 练习推荐题目
    handlePracticeRecommended() {
      if (this.selectedRecommendedQuestions.length === 0) {
        this.$message.warning('请选择要练习的题目')
        return
      }
      console.log('this.selectedRecommendedQuestions',this.selectedRecommendedQuestions)
      this.$router.push({
        path: '/wrongQuestion/practice',
        query: {questionIds: this.selectedRecommendedQuestions.join(',')}
      })
    },

    // 练习单题
    handlePracticeOne(record) {
      this.$router.push({
        path: '/wrongQuestion/practice',
        query: {recordId: record.id}
      })
    },

    // 开始练习
    handlePractice() {
      if (this.selectedRecordIds.length === 0) {
        this.$message.warning('请选择要练习的错题')
        return
      }
      this.$router.push({
        path: '/wrongQuestion/practice',
        query: {recordIds: this.selectedRecordIds.join(',')}
      })
    },

    // 显示统计
    showStats() {
      this.statsVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.record-card {
  margin-bottom: 20px;

  .record-title {
    margin-left: 10px;
    font-weight: bold;
  }

  .record-content {
    padding: 10px 0;
    border-bottom: 1px solid #ebeef5;
    min-height: 60px;
  }

  .record-meta {
    display: flex;
    padding: 10px 0;
    font-size: 13px;
    color: #666;

    .meta-item {
      flex: 1;
      display: flex;
      align-items: center;

      .meta-label {
        margin-right: 5px;
        font-weight: bold;
      }
    }
  }

  .record-actions {
    text-align: right;
    padding-top: 10px;
    border-top: 1px solid #ebeef5;
  }
}

.mb-20 {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.question-title {
  font-weight: bold;
  margin-bottom: 8px;
}

.question-content {
  margin-top: 8px;
}

.el-progress {
  display: inline-block;
  width: 80px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
